package com.wanggsx.library.base.views.viewpager.carditem;

import androidx.viewpager.widget.PagerAdapter;
import androidx.cardview.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public abstract class CardPagerAdapter<T extends CardItem> extends PagerAdapter implements CardAdapter {

    private List<CardView> mViews;
    private List<T> mData;
    private float mBaseElevation;
    private int mItemLayoutId, mCardViewId;

    public CardPagerAdapter(int itemLayoutId, int cardViewId) {
        mData = new ArrayList<>();
        mViews = new ArrayList<>();
        mItemLayoutId = itemLayoutId;
        mCardViewId = cardViewId;
    }

    public void addCardItem(T item) {
        mViews.add(null);
        mData.add(item);
    }

    public T getData(int position){
        if (mData==null || mData.size()<position+1){
            return null;
        }else{
            return mData.get(position);
        }
    }

    public CardView getCardView(int position) {
        return mViews.get(position);
    }

    public float getBaseElevation() {
        return mBaseElevation;
    }

    @Override
    public CardView getCardViewAt(int position) {
        return mViews.get(position);
    }

    @Override
    public int getCount() {
        if (mData == null) {
            return 0;
        } else {
            return mData.size();
        }
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = LayoutInflater.from(container.getContext())
                .inflate(mItemLayoutId, container, false);
        container.addView(view);
        bind(mData.get(position), view);
        CardView cardView = (CardView) view.findViewById(mCardViewId);
        if (mBaseElevation == 0) {
            mBaseElevation = cardView.getCardElevation();
        }
        cardView.setMaxCardElevation(mBaseElevation * MAX_ELEVATION_FACTOR);
        mViews.set(position, cardView);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        mViews.set(position, null);
    }

    public abstract void bind(T item, View view);

}